package com.das.mechanic_base.utils;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.camera.X3CameraPreviewAdapter;
import com.das.mechanic_base.adapter.camera.X3CameraPreviewAdapter2;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3MyApp;
import com.das.mechanic_base.bean.alone.AloneNewBean;
import com.das.mechanic_base.bean.alone.AlonePicVideoBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.greendao.AloneServiceListBean;
import com.das.mechanic_base.bean.greendao.AloneServiceNewBean;
import com.das.mechanic_base.mvp.view.camera.X3CameraPhotoActivity;
import com.das.mechanic_base.widget.X3AloneCameraInstructionDialog;
import com.das.mechanic_base.widget.X3MyRecyclerview;
import com.kproduce.roundcorners.RoundRelativeLayout;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class X3AloneLayoutUtils {

    private Context mContext;
    private View cameraView;
    private RelativeLayout rl_top;
    private RelativeLayout fl_ins;
    private RelativeLayout fl_whole;
    private TextView tv_pic;
    private TextView tv_video;
    private int videoTime;
    private TextView tv_min;
    private ProgressBar pb_bar;
    private CameraView cv_view;
//    private CardView cv_view_parent;
    private CardView cv_nest;
    private View cv_view_parent;
    private X3CameraPreviewAdapter2 previewAdapter;
    private int allNum;
    private View v_bg;
    private ObjectAnimator closeAnim;
    private ObjectAnimator scaleXY;
    private ObjectAnimator alphaXY;
    private ImageView iv_light;
    private RecyclerView rlv_camera;
    private RelativeLayout rl_video;
    private ScaleGestureDetector mScaleGestureDetector  ;

    private int cameraMode;

    public X3AloneLayoutUtils(Context mContext) {
        this.mContext = mContext;
        initScaleGestureDetector(mContext);
    }

    public View createAloneTitle(Context mContext, AloneNewBean.ItemQuestionListBean itemBean,LinearLayout al_container,int index,IOnCreateTitle iOnCreateTitle) {
        View titleView = getParentTitleView(index, itemBean.toItemDesc);

        if (itemBean == null) {
            return titleView;
        }
        List<AloneNewBean.ItemQuestionListBean.QuestionDetectionTempletQuestionListBean> aloneBeans = itemBean.questionDetectionTempletQuestionList;
        if (X3StringUtils.isListEmpty(aloneBeans)) {
            aloneBeans = new ArrayList<>();
        }
        /**
         * 创建检测项title
         */
        int num = aloneBeans.size();
        String point_check = (num == 1) ? String.format(mContext.getString(R.string.x3_main_tain_num), num) : String.format(mContext.getString(R.string.x3_main_tain_nums), num);
        al_container.addView(titleView);
        TextView tv_point = titleView.findViewById(R.id.tv_point);
//        TextView tv_pass = titleView.findViewById(R.id.tv_pass);
        tv_point.setText(point_check + "");

        // 检测点标记通过
//        tv_pass.setOnClickListener(view -> {
//            List<AloneNewBean.ItemQuestionListBean> passBean = new ArrayList<>();
//            passBean.add(itemBean);
//            if (iOnCreateTitle != null) {
//                iOnCreateTitle.iOnPassTitle(passBean,false);
//            }
//        });

        TextView studyView = new TextView(mContext);
        LinearLayout.LayoutParams studyLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        studyLayout.leftMargin = X3ScreenUtils.dipToPx(12,mContext);
        studyView.setPadding(X3ScreenUtils.dipToPx(10,mContext), X3ScreenUtils.dipToPx(10,mContext), X3ScreenUtils.dipToPx(10,mContext), X3ScreenUtils.dipToPx(10,mContext));
        studyView.setLayoutParams(studyLayout);
        al_container.addView(studyView);

        Drawable drawable = ContextCompat.getDrawable(mContext,R.mipmap.x3_alone_sample_icon);
        drawable.setBounds(X3ScreenUtils.dipToPx(5,mContext), 0, drawable.getMinimumWidth() + X3ScreenUtils.dipToPx(5,mContext), drawable.getMinimumHeight());
        studyView.setCompoundDrawables(null, null, drawable, null);
        studyView.setText(mContext.getString(R.string.x3_alone_sample));
        studyView.setTextColor(ContextCompat.getColor(mContext,R.color.c0077ff));

        String normalVideoUrl = itemBean.normalVideoUrl;
        if (X3StringUtils.isEmpty(normalVideoUrl)) {
            studyView.setVisibility(View.GONE);
        }

        /**
         * 跳转到检测实例 视频
         */
        studyView.setOnClickListener(v -> {
            List<String> mList = new ArrayList<>();
            mList.add(normalVideoUrl);
            X3Utils.startShowImage(mContext,mList,0);
        });
        return titleView;
    }

    public interface IOnCreateTitle {
        void iOnPassTitle(List<AloneNewBean.ItemQuestionListBean> passBean,boolean isAll);
    }

    /**
     * 创建检测项顶级view
     * @return
     */
    public LinearLayout getParentLinearLayout() {
        LinearLayout lv_content = new LinearLayout(mContext);
        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentParams.bottomMargin = X3ScreenUtils.dipToPx(8,mContext);
        lv_content.setLayoutParams(contentParams);
        lv_content.setOrientation(LinearLayout.VERTICAL);
        return lv_content;
    }

    /**
     * 创建每一个检测点的
     * @return
     */
    public LinearLayout getPointLinearLayout() {
        LinearLayout lv_content = new LinearLayout(mContext);
        lv_content.setBackground(ContextCompat.getDrawable(mContext,R.drawable.x3_alone_point_bg2));
        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentParams.bottomMargin = X3ScreenUtils.dipToPx(16,mContext);
        contentParams.leftMargin = X3ScreenUtils.dipToPx(16,mContext);
        contentParams.rightMargin = X3ScreenUtils.dipToPx(16,mContext);
        contentParams.topMargin = X3ScreenUtils.dipToPx(0,mContext);
        lv_content.setLayoutParams(contentParams);
        lv_content.setOrientation(LinearLayout.VERTICAL);
        return lv_content;
    }

    /**
     * 创建检测项title
     * @param index
     * @return
     */
    public View getParentTitleView(int index,String title) {
        View titleView = View.inflate(mContext, R.layout.x3_alone_title_item,null);
        TextView tv_title = titleView.findViewById(R.id.tv_title);
        titleView.setOnClickListener(view -> {
            if (iOnAloneClick != null) {
                iOnAloneClick.iOnAloneClickTitle(index);
            }
        });

        titleView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        if (!X3StringUtils.isEmpty(title)) {
            tv_title.setText(title);
        }
        return titleView;
    }

    /**
     * 拍照与录音
     * @return
     */
    public X3MyRecyclerview getPhotoRecyclerview() {
        // 拍照与录音
        X3MyRecyclerview photoRecy = new X3MyRecyclerview(mContext);
        photoRecy.setNestedScrollingEnabled(false);
        photoRecy.setLayoutManager(new GridLayoutManager(mContext,3));
//        ((DefaultItemAnimator)photoRecy.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.leftMargin = X3ScreenUtils.dipToPx(16, mContext);
        layoutParams1.rightMargin = X3ScreenUtils.dipToPx(16, mContext);
        layoutParams1.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
        layoutParams1.topMargin = X3ScreenUtils.dipToPx(15,mContext);
        photoRecy.setLayoutParams(layoutParams1);
        return photoRecy;
    }

    /**
     * 初检 拍照与录音
     * @return
     */
    public X3MyRecyclerview getDetectionRecyclerview() {
        // 拍照与录音
        X3MyRecyclerview photoRecy = new X3MyRecyclerview(mContext);
        photoRecy.setNestedScrollingEnabled(false);
        photoRecy.setLayoutManager(new GridLayoutManager(mContext,3));
        ((DefaultItemAnimator)photoRecy.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.leftMargin = X3ScreenUtils.dipToPx(16, mContext);
        layoutParams1.rightMargin = X3ScreenUtils.dipToPx(16, mContext);
        layoutParams1.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
        photoRecy.setLayoutParams(layoutParams1);
        return photoRecy;
    }

    /**
     * 检测项之间的分割线
     * @return
     */
    public View getTitleLineView() {
        View lineView = new View(mContext);
        lineView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, X3ScreenUtils.dipToPx(10,mContext)));
        lineView.setBackgroundColor(Color.parseColor("#F5F5F7"));
        return lineView;
    }

    /**
     * 检测点的评论
     * @return
     */
    public View getItemCommentView() {
//        View lineView = new View(mContext);
        View lineView = View.inflate(mContext, R.layout.x3_alone_item_comment,null);
//        LinearLayout.LayoutParams point = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, X3ScreenUtils.dipToPx(50,mContext));
//        point.leftMargin = X3ScreenUtils.dipToPx(16,mContext);
//        point.rightMargin = X3ScreenUtils.dipToPx(16,mContext);
//        point.topMargin = X3ScreenUtils.dipToPx(10,mContext);
//        point.bottomMargin = X3ScreenUtils.dipToPx(20,mContext);
//        lineView.setLayoutParams(point);
        return lineView;
    }

    /**
     * 检测点的评论
     * @return
     */
    public View getBottomView() {
        View view = new View(mContext);
        LinearLayout.LayoutParams point = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        return view;
    }

    IOnAloneClick iOnAloneClick;

    public void setiOnAloneClick(IOnAloneClick iOnAloneClick) {
        this.iOnAloneClick = iOnAloneClick;
    }

    public interface IOnAloneClick {
        /**
         * 点击title 实现展开或者关闭
         * @param index
         */
        void iOnAloneClickTitle(int index);
    }

    // 图片
    private List<String> imgList;

    // 视频
    private List<String> videoList;

    // 视频图片总体集合
    private List<AlonePicVideoBean> videoImagList;

    public View getCv_view() {
        return cameraView;
    }


    //滑动的时候，只切换拍照和录像不进行单击操作
    boolean resetCamera;
    //正在滑动不要相应长安操作
    boolean isMoveIng;

    /**
     * 相机账号设置
     * viewGroup 顶级并且子View数量可大于1的viewgroup
     * allNum 还可拍摄的总数量
     * imageUrl 示例图
     */
    public void startCamera(Activity activity,ViewGroup viewGroup,long questionTemId,long workBaseId,int allNum,String imageUrl,boolean isWork,IOnGetPictureOrVideo iOnGetPictureOrVideo) {
        if (!X3Utils.isFastClick()) {
            return;
        }
        this.allNum = allNum;
        String mobile = (String) SpHelper.getData("mobile", "");
        /**
         * 先查询是否对此施工单做了单独的拍摄模式的设置
         * 没有的话 则获取全局默认的拍摄模式的设置
         */
        cameraMode = (int) SpHelper.getData(mobile + X3Constent.QUICK_CAMERA_MODE + workBaseId, -1);
        if (cameraMode == -1) {
            cameraMode = (int) SpHelper.getData(mobile + X3Constent.QUICK_CAMERA_MODE, 2);
        }

        if (cameraMode == 0 || cameraMode == 1) {
            X3StatusBarUtil.setStatusBar(activity,Color.parseColor("#B3000000"));
            if (cameraView == null) {
                cameraView = View.inflate(mContext,R.layout.x3_camera_model_layout,null);
                viewGroup.addView(cameraView);
                cv_view = cameraView.findViewById(R.id.cv_view);
                cv_view_parent = cameraView.findViewById(R.id.cv_view_parent);
                cv_nest = cameraView.findViewById(R.id.cv_nest);

                getCameraData(iOnGetPictureOrVideo,isWork);

            }else {
                ViewGroup parent = (ViewGroup) cameraView.getParent();
                if (parent != null) {
                    parent.removeView(cameraView);
                }
                viewGroup.addView(cameraView);
            }
            MobclickAgent.onPageStart(cameraMode == 0 ? "快速拍照模式弹窗" : "快速录像模式弹窗");
            cv_view.setMode(cameraMode == 0 ? Mode.PICTURE : Mode.VIDEO);

            ViewGroup.LayoutParams cameraLayout = cameraView.getLayoutParams();
            cameraLayout.width = ViewGroup.LayoutParams.MATCH_PARENT;
            cameraLayout.height = ViewGroup.LayoutParams.MATCH_PARENT;
            cameraView.setLayoutParams(cameraLayout);

            RelativeLayout rl_camera = cameraView.findViewById(R.id.rl_camera);
            View v_click = cameraView.findViewById(R.id.v_click);
             rl_video = cameraView.findViewById(R.id.rl_video);
            tv_min = cameraView.findViewById(R.id.tv_min);
            pb_bar = cameraView.findViewById(R.id.pb_bar);
            v_bg = cameraView.findViewById(R.id.v_bg);
            iv_light = cameraView.findViewById(R.id.iv_light);

            fl_ins = cameraView.findViewById(R.id.fl_ins);
            fl_whole = cameraView.findViewById(R.id.fl_whole);
            tv_pic = cameraView.findViewById(R.id.tv_pic);
            tv_video = cameraView.findViewById(R.id.tv_video);

            rlv_camera = cameraView.findViewById(R.id.rlv_camera);
            rlv_camera.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
            previewAdapter = new X3CameraPreviewAdapter2(mContext);
            rlv_camera.setAdapter(previewAdapter);
            previewAdapter.changeIsDelete(false);

            initCameraView();

            tv_pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (X3Utils.isFastClick3()) {
                        return;
                    }
                    changeModel(1);
                }
            });

            tv_video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (X3Utils.isFastClick4()) {
                        return;
                    }
                    changeModel(2);
                }
            });

            fl_ins.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    X3AloneCameraInstructionDialog dailogDetail = new X3AloneCameraInstructionDialog(X3MyApp.getInstance().getTopActivity());
                    dailogDetail.setiBtnClick(new X3AloneCameraInstructionDialog.IBtnClick() {
                        @Override
                        public void iBtnAffirmClick() {

                            if (cv_view.isTakingVideo()) {
                                return ;
                            }
                            ViewGroup parent = (ViewGroup) cameraView.getParent();
                            if (parent != null) {
                                parent.removeView(cameraView);
                            }
                            int i = allNum - imgList.size() - videoList.size();
                            if (i <= 0) {
                                X3ToastUtils.showMessage(String.format(mContext.getString(R.string.x3_upload_mast_nine), allNum));
                                return ;
                            }
//                            X3StatusBarUtil.setStatusBar(activity,Color.TRANSPARENT);
                            X3StatusBarUtil.darkMode(activity);
                            jumpToCamera(i, imageUrl, cv_view.getMode(), questionTemId, isWork);

                        }
                    });
                    dailogDetail.show();
                }
            });

            //完整模式
            fl_whole.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    X3StatusBarUtil.setStatusBar(activity,Color.TRANSPARENT);
                    X3StatusBarUtil.darkMode(activity);
                    toWholeModel(imageUrl,questionTemId,isWork);

                }
            });

            iv_light.setOnClickListener(v -> {
                Flash flash = cv_view.getFlash();
                if (Flash.TORCH == flash) {
                    cv_view.setFlash(Flash.OFF);
                    iv_light.setImageResource(R.mipmap.x3_light_off);
                } else {
                    cv_view.setFlash(Flash.TORCH);
                    iv_light.setImageResource(R.mipmap.x3_light_on);
                }
            });

            //点击外层关闭拍照界面
            rl_camera.setOnClickListener(view -> {
                closeCamera();
//                X3StatusBarUtil.setStatusBar(activity,Color.parseColor("#B3000000"));
//                X3StatusBarUtil.setStatusBar(activity,Color.TRANSPARENT);
                X3StatusBarUtil.darkMode(activity);

//                if (cv_view.getFlash() == Flash.TORCH) {
//                    iv_light.performClick();
//                }
//                cv_view.setFlash(Flash.OFF);
//                iv_light.setImageResource(R.mipmap.x3_light_off);
//                changeModel(1);
//                cv_view.setZoom(0);
//                new Handler().postDelayed(() -> exitCamera(),200);

            });

            rl_video.setVisibility(cameraMode == 0 ? View.GONE : View.VISIBLE);

            v_click.setOnLongClickListener(view -> {
                if(!isMoveIng) {
//                    X3StatusBarUtil.setStatusBar(activity,Color.TRANSPARENT);
                    X3StatusBarUtil.darkMode(activity);
                    toWholeModel(imageUrl,questionTemId,isWork);
                }
                return true;
            });

            v_click.setOnTouchListener(new View.OnTouchListener() {

                int startX, startY, endX, endY, lastX, lastY;

                @Override
                public boolean onTouch(View v, MotionEvent event) {

//                    switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    switch (event.getActionMasked()) {

                        case MotionEvent.ACTION_DOWN:
                            resetCamera = false;
                            isMoveIng = false;
                            startX = (int) event.getX();
                            startY = (int) event.getY();
                            break;
                        case MotionEvent.ACTION_MOVE:
                            int pointerCount = event.getPointerCount();

                            endX = (int) event.getX();
                            endY = (int) event.getY();

                            if (pointerCount == 2) {
                                isMoveIng = true;
                                resetCamera = true;
                                mScaleGestureDetector.onTouchEvent(event);
                            } else if (pointerCount == 1){
                                if (Math.abs(startX - endX) > 20) {
                                    isMoveIng = true;
                                }
                                if (Math.abs(startX - endX) > 100 && !resetCamera) {
                                    resetCamera = true;
                                    if (cv_view.isTakingVideo()) {
                                        break;
                                    }

                                    resetVideo();
                                    if (v_bg != null) {
                                        alphaXY = X3AnimationUtils.alphaXY(v_bg, 400);
                                        alphaXY.start();
                                    }

                                    if (cv_view.getMode() == Mode.PICTURE) {
                                        cv_view.setMode(Mode.VIDEO);
                                        rl_video.setVisibility(View.VISIBLE);
                                        tv_pic.setTextColor(Color.parseColor("#ffffff"));
                                        tv_video.setTextColor(Color.parseColor("#313340"));
                                        tv_pic.setBackgroundResource(0);
                                        tv_video.setBackgroundResource(R.drawable.x3_shape_camera_selected_bg);
                                    } else {
                                        cv_view.setMode(Mode.PICTURE);
                                        rl_video.setVisibility(View.GONE);
                                        tv_video.setTextColor(Color.parseColor("#ffffff"));
                                        tv_pic.setTextColor(Color.parseColor("#313340"));
                                        tv_video.setBackgroundResource(0);
                                        tv_pic.setBackgroundResource(R.drawable.x3_shape_camera_selected_bg);
                                    }
                                    showPicVideo("");
                                }
                            }

                            break;
                        case MotionEvent.ACTION_POINTER_DOWN:
                            isMoveIng = true;
                            resetCamera = true;
                            break;
                        case MotionEvent.ACTION_UP:
                        case MotionEvent.ACTION_CANCEL:
                            break;
                    }
                    return false;
                }
            });

            v_click.setOnClickListener(new X3DoubleClickListener(new X3DoubleClickListener.DoubleClickCallBack() {
                @Override
                public void oneClick(View view) {
                    if (!resetCamera) {
                        if ((videoList.size() + imgList.size() >= allNum)) {
                            X3ToastUtils.showMessage(String.format(mContext.getString(R.string.x3_upload_mast_nine), allNum));
                            return;
                        }
                        if (cv_view.getMode() == Mode.PICTURE) {
                            // 拍照
                            cv_view.takePictureSnapshot();
                        } else {
                            // 录像
                            startRecord();
                        }
                    }
                }

                @Override
                public void doubleClick(View view) {
                    if (!X3Utils.isFastClick()) {
                        return;
                    }
                    Flash flash = cv_view.getFlash();
                    if (Flash.TORCH == flash) {
                        cv_view.setFlash(Flash.OFF);
                        iv_light.setImageResource(R.mipmap.x3_light_off);
                    }else {
                        cv_view.setFlash(Flash.TORCH);
                        iv_light.setImageResource(R.mipmap.x3_light_on);
                    }
                }
            }));
        }else {
            jumpToCamera(allNum,imageUrl,null,questionTemId,isWork);
        }
    }

    private void initScaleGestureDetector(Context mContext){
        mScaleGestureDetector = new ScaleGestureDetector(mContext, new ScaleGestureDetector.OnScaleGestureListener() {
            @Override
            public boolean onScale(ScaleGestureDetector detector) {
                float scale = detector.getScaleFactor();
                if (scale >= 1) {
                    cv_view.setZoom(cv_view.getZoom() + (Math.abs(1 - scale)));
                } else {
                    cv_view.setZoom(cv_view.getZoom() - (Math.abs(1 - scale)));
                }

                return true;
            }

            @Override
            public boolean onScaleBegin(ScaleGestureDetector detector) {
                return true;
            }

            @Override
            public void onScaleEnd(ScaleGestureDetector detector) {

            }
        });
    }

    private void closeCamera(){
        if (cv_view.getFlash() == Flash.TORCH) {
            iv_light.performClick();
        }
        currentType = 1;
        cv_view.setFlash(Flash.OFF);
        iv_light.setImageResource(R.mipmap.x3_light_off);
//        changeModel(1);
        cv_view.setZoom(0);
        new Handler().postDelayed(() -> exitCamera(),200);
    }

    /**
     * 切换到完整拍照模式
     */
    private void toWholeModel(String imageUrl,long questionTemId, boolean isWork){
        if (cv_view.isTakingVideo()) {
            return ;
        }
        ViewGroup parent = (ViewGroup) cameraView.getParent();
        if (parent != null) {
            parent.removeView(cameraView);
        }

        cv_view.setFlash(Flash.OFF);
        iv_light.setImageResource(R.mipmap.x3_light_off);
        currentType = 1;

        int i = allNum - imgList.size() - videoList.size();
        if (i <= 0) {
            X3ToastUtils.showMessage(String.format(mContext.getString(R.string.x3_upload_mast_nine), allNum));
            return ;
        }
        jumpToCamera(i, imageUrl, cv_view.getMode(), questionTemId, isWork);
    }


    int currentType = 1;
    /**
     * 切换拍照和录像
     */
    private void changeModel(int type){
        if (currentType != type){
            currentType = type;
        }else{
            return;
        }
        resetCamera = true;
        if (cv_view.isTakingVideo()) {
            return;
        }

        resetVideo();
        if (v_bg != null) {
            alphaXY = X3AnimationUtils.alphaXY(v_bg, 400);
            alphaXY.start();
        }

        if (2 == type) { // 视频
            cv_view.setMode(Mode.VIDEO);
            rl_video.setVisibility(View.VISIBLE);
            tv_pic.setTextColor(Color.parseColor("#ffffff"));
            tv_video.setTextColor(Color.parseColor("#313340"));
            tv_pic.setBackgroundResource(0);
            tv_video.setBackgroundResource(R.drawable.x3_shape_camera_selected_bg);
        } else {
            cv_view.setMode(Mode.PICTURE);
            rl_video.setVisibility(View.GONE);
            tv_video.setTextColor(Color.parseColor("#ffffff"));
            tv_pic.setTextColor(Color.parseColor("#313340"));
            tv_video.setBackgroundResource(0);
            tv_pic.setBackgroundResource(R.drawable.x3_shape_camera_selected_bg);
        }
        showPicVideo("");
    }

    /**
     * 展示视频和图片
     */
    private void showPicVideo(String path){

        if (previewAdapter != null) {
            boolean hasContain = false;
            if (videoImagList != null ){
                for (AlonePicVideoBean bean : videoImagList){
                    if (!X3StringUtils.isEmpty(path) && path.equals(bean.path)){
                        hasContain = true;
                        break;
                    }
                }
            }

            if(!hasContain && !X3StringUtils.isEmpty(path)){
                AlonePicVideoBean addBean = new AlonePicVideoBean();
                addBean.path = path;
                addBean.mode = Mode.VIDEO;
                videoImagList.add(addBean);
            }
            previewAdapter.changeCameraList(videoImagList);
            rlv_camera.scrollToPosition(videoImagList.size()-1);
        }
    }

    /**
     * 计算两个点的距离
     *
     * @param event
     * @return
     */
    private float spacing(MotionEvent event) {
        if (event.getPointerCount() == 2) {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return (float) Math.sqrt(x * x + y * y);
        } else {
            return 0;
        }
    }

    /**
     * 初始化cameraView
     */
    private void initCameraView() {
        imgList = new ArrayList<>();
        videoList = new ArrayList<>();
        videoImagList = new ArrayList<>();

//        changeModel(1);
        tv_video.setTextColor(Color.parseColor("#ffffff"));
        tv_pic.setTextColor(Color.parseColor("#313340"));
        tv_video.setBackgroundResource(0);
        tv_pic.setBackgroundResource(R.drawable.x3_shape_camera_selected_bg);

        resetVideo();

        iv_light.setImageResource(R.mipmap.x3_light_off);

        ViewGroup.LayoutParams layoutParams2 = cv_nest.getLayoutParams();
        layoutParams2.height = (X3ScreenUtils.getScreenWidth(mContext) - X3ScreenUtils.dipToPx(32,mContext)) * 4 / 3;
        cv_nest.setLayoutParams(layoutParams2);

        ViewGroup.LayoutParams layoutParams1 = cv_view_parent.getLayoutParams();
        layoutParams1.height = (X3ScreenUtils.getScreenWidth(mContext) - X3ScreenUtils.dipToPx(32,mContext)) * 4 / 3;
        cv_view_parent.setLayoutParams(layoutParams1);

        ViewGroup.LayoutParams layoutParams = cv_view.getLayoutParams();
        layoutParams.height = (X3ScreenUtils.getScreenWidth(mContext) - X3ScreenUtils.dipToPx(32,mContext)) * 4 / 3;
        cv_view.setLayoutParams(layoutParams);

        cameraView.setPivotY((X3ScreenUtils.getScreenHeight(mContext) - layoutParams.height) / 2);
        cameraView.setPivotX(X3ScreenUtils.getScreenWidth(mContext) / 2);
        scaleXY = X3AnimationUtils.scaleXY(cameraView);
        if (scaleXY != null) {
            scaleXY.start();
        }
        cv_view.setLifecycleOwner((LifecycleOwner) mContext);
    }

    /**
     * 重设拍摄视频的功能
     */
    private void resetVideo() {
        videoTime = 0;
        tv_min.setText("00:00");
        pb_bar.setProgress(0);

        if (cv_view.isTakingVideo()) {
            cv_view.stopVideo();
        }
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
    }

    /**
     * 设置拍照录像监听 只能设置一次
     * @param iOnGetPictureOrVideo
     */
    private void getCameraData(IOnGetPictureOrVideo iOnGetPictureOrVideo,boolean isWork) {
        cv_view.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                super.onPictureTaken(result);
                if (videoList.size() + imgList.size() >= allNum) {
                    return;
                }
                File imgFile = new File(X3FileUtils.getStoragePath(mContext, X3FileUtils.MECHANIC_PHOTO_STORAGE_PATH) + "work_tain" + System.currentTimeMillis() + ".jpg");
                if (!imgFile.getParentFile().exists()) {
                    imgFile.getParentFile().mkdirs();
                }
                if (!imgFile.exists()) {
                    try {
                        imgFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                result.toFile(imgFile, file2 -> {
                    // 获取图片地址
                    if (v_bg != null) {
                        alphaXY = X3AnimationUtils.alphaXY(v_bg,200);
                        alphaXY.start();
                    }

                    List<String> list = new ArrayList<>();
                    list.add(file2.getPath());
                    CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST, list);
                    cameraBean.isWork = isWork;
                    if (iOnGetPictureOrVideo != null) {
                        iOnGetPictureOrVideo.iOnGetSuccess(cameraBean);
                    }
                    imgList.add(file2.getPath());
                    showPicVideo(file2.getPath());
//                    if (previewAdapter != null) {
//                        previewAdapter.changeCameraList(imgList,Mode.PICTURE);
//                    }
                    if (videoList.size() + imgList.size() >= allNum) {
                        // 销毁
                        closeAnim = X3AnimationUtils.scaleCloseXY(cameraView);
                        if (closeAnim != null) {
                            closeAnim.start();
                        }

                        closeCamera();

                    }
                });
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                super.onVideoTaken(result);
                if (videoList.size() + imgList.size() >= allNum) {
                    return;
                }
                if (v_bg != null) {
                    alphaXY = X3AnimationUtils.alphaXY(v_bg,200);
                    alphaXY.start();
                }

                // 获取视频地址
                String path = result.getFile().getPath();
                videoList.add(path);

                showPicVideo(path);

                List<String> vList = new ArrayList<>();
                vList.add(path);
                CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST, vList);
                cameraBean.isWork = isWork;
                if (iOnGetPictureOrVideo != null) {
                    iOnGetPictureOrVideo.iOnGetSuccess(cameraBean);
                }
                resetVideo();

                if (videoList.size() + imgList.size() >= allNum) {
                    // 销毁
                    closeAnim = X3AnimationUtils.scaleCloseXY(cameraView);
                    if (closeAnim != null) {
                        closeAnim.start();
                    }
                    closeCamera();
                }
            }
        });
    }

    /**
     * 开启录像
     */
    private void startRecord() {
        if (cv_view.isTakingVideo()) {
            resetVideo();
            return;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String videoSavePath = X3FileUtils.getStoragePath(mContext, X3FileUtils.MECHANIC_VIDEO_STORAGE_PATH) + "VIDEO_" + timeStamp + ".mp4";
        cv_view.takeVideoSnapshot(new File(videoSavePath));
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
            mHandler.postDelayed(runnable,100);
        }
    }

    private Handler mHandler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (videoTime < 15 * 1000) {
                videoTime += 100;
                if (tv_min != null) {
                    int i = videoTime / 1000;
                    int i1 = videoTime % 1000 / 10;
                    tv_min.setText(((i < 10) ? "0" + i : i) + ":" + ((i1 < 10) ? "0" + i1 : i1));
                }
                if (pb_bar != null) {
                    pb_bar.setProgress(videoTime);
                }
                mHandler.postDelayed(this,100);
            }else {
                cv_view.stopVideo();
                mHandler.removeCallbacks(runnable);
            }
        }
    };

    public void onDestory(){
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        if (cv_view!=null && cv_view.getFlash()!=null && cv_view.getFlash() == Flash.TORCH) {
            cv_view.setFlash(Flash.OFF);
            iv_light.setImageResource(R.mipmap.x3_light_on);
        }

        if (alphaXY != null) {
            alphaXY.cancel();
        }
        if (scaleXY != null) {
            scaleXY.cancel();
        }
        if (closeAnim != null) {
            closeAnim.cancel();
        }
    }

    public void exitCamera() {
        MobclickAgent.onPageEnd(cameraMode == 0 ? "快速拍照模式弹窗" : "快速录像模式弹窗");
        if (cv_view != null && cv_view.isTakingVideo()) {
            cv_view.stopVideo();
            if (mHandler != null) {
                mHandler.removeCallbacks(runnable);
            }
        }else {
            closeAnim = X3AnimationUtils.scaleCloseXY(cameraView);
            if (closeAnim != null) {
                closeAnim.start();
            }
        }

        onDestory();
    }

    /**
     * 跳转到完整的拍照页面
     * @param allNum
     * @param imageUrl
     */
    private void jumpToCamera(int allNum,String imageUrl,Mode mode,long questionItemId,boolean isWork) {
        jumpToCamera(allNum,imageUrl,mode,questionItemId,isWork,false);
    }

    /**
     * 跳转到完整的拍照页面
     * @param allNum
     * @param imageUrl
     */
    private void jumpToCamera(int allNum,String imageUrl,Mode mode,long questionItemId,boolean isWork,boolean isFastMode) {
        Intent intent = new Intent(mContext, X3CameraPhotoActivity.class);
        intent.putExtra("allNum",allNum);
        intent.putExtra("imgUrl",imageUrl);
        intent.putExtra("itemId",questionItemId);
        intent.putExtra("isWork",isWork);
        if (mode != null) {
            intent.putExtra("normal_select",mode == Mode.PICTURE ? 2 : 1);
        }
        mContext.startActivity(intent);
        ((Activity)mContext).overridePendingTransition(R.anim.activity_enter, 0);
    }

    public interface IOnGetPictureOrVideo {
        void iOnGetSuccess(CameraBean cameraBean);
    }

    /**
     * 将购物车数据转换为我们使用的数据
     * @param mList
     * @return
     */
    public static List<AloneServiceListBean> getCurrentServiceList(List<AloneServiceNewBean> mList) {
        if (X3StringUtils.isListEmpty(mList)) {
            return new ArrayList<>();
        }
        HashMap<String,AloneServiceListBean> serviceMap = new HashMap<>();
        for (int i = 0; i < mList.size(); i++) {
            long questionBaseId = mList.get(i).questionBaseId;
            List<AloneServiceNewBean.DetectionTouchServiceEntityListBean> dList = mList.get(i).detectionTouchServiceEntityList;
            for (int j =0; j < dList.size(); j++){
                AloneServiceNewBean.DetectionTouchServiceEntityListBean detectionBean = dList.get(j);

                String touchServiceBaseName = detectionBean.touchServiceBaseName;
                List<AloneServiceListBean.IdBean> detectionIdOptions = detectionBean.questionAndOptionIdVOList;

                if (serviceMap.containsKey(touchServiceBaseName)) {
                    AloneServiceListBean aloneServiceListBean = serviceMap.get(touchServiceBaseName);
                    List<AloneServiceListBean.IdBean> questionAndOptionIdVOList = aloneServiceListBean.getQuestionAndOptionIdVOList();
                    List<Long> idList = aloneServiceListBean.getTouchQuestionBaseIdList();
                    if (X3StringUtils.isListEmpty(idList)) {
                        idList = new ArrayList<>();
                    }
                    if (X3StringUtils.isListEmpty(detectionIdOptions)) {
                        questionAndOptionIdVOList.add(new AloneServiceListBean.IdBean(questionBaseId,0));
                        idList.add(questionBaseId);
                    }else {
                        boolean isAdd = false;
                        for (int d = 0; d < detectionIdOptions.size(); d++) {
                            AloneServiceListBean.IdBean idBean = detectionIdOptions.get(d);
                            if (idBean.getQuestionBaseId() == questionBaseId) {
                                questionAndOptionIdVOList.add(idBean);
                                isAdd = true;
                            }
                        }

                        if (!isAdd) {
                            questionAndOptionIdVOList.add(new AloneServiceListBean.IdBean(questionBaseId,0));
                        }
                        if (!idList.contains(questionBaseId)) {
                            idList.add(questionBaseId);
                        }
                    }
                    aloneServiceListBean.setTouchQuestionBaseIdList(idList);
                    aloneServiceListBean.setQuestionAndOptionIdVOList(questionAndOptionIdVOList);
                    serviceMap.put(touchServiceBaseName,aloneServiceListBean);

                }else {
                    AloneServiceListBean serviceBean = new AloneServiceListBean();
                    serviceBean.setReductionType(detectionBean.reductionType);
                    serviceBean.setWarningDate(detectionBean.warningDate);
                    serviceBean.setRecommendSafeMiles(detectionBean.recommendSafeMiles);
                    serviceBean.setPerMiles(detectionBean.perMiles);
                    serviceBean.setCurrentMiles(detectionBean.currentMiles);
                    serviceBean.setCarId(detectionBean.carId);
                    serviceBean.setTouchServiceSn(detectionBean.touchServiceSn);
                    serviceBean.setTouchServiceBaseName(detectionBean.touchServiceBaseName);
                    serviceBean.setWorkBaseId(detectionBean.workBaseId);
                    serviceBean.setTouchQuestionBaseDescriptionList(detectionBean.touchQuestionBaseDescriptionList);
                    serviceBean.setTouchQuestionBaseIdList(detectionBean.touchQuestionBaseIdList);

                    List<AloneServiceListBean.IdBean> questionAndOptionIdVOList = new ArrayList<>();
                    if (X3StringUtils.isListEmpty(detectionIdOptions)) {
                        questionAndOptionIdVOList.add(new AloneServiceListBean.IdBean(questionBaseId,0));
                    }else {
                        boolean isAdd = false;
                        for (int d = 0; d < detectionIdOptions.size(); d++) {
                            AloneServiceListBean.IdBean idBean = detectionIdOptions.get(d);
                            if (idBean.getQuestionBaseId() == questionBaseId) {
                                questionAndOptionIdVOList.add(idBean);
                                isAdd = true;
                            }
                        }
                        if (!isAdd) {
                            questionAndOptionIdVOList.add(new AloneServiceListBean.IdBean(questionBaseId,0));
                        }
                    }
                    serviceBean.setQuestionAndOptionIdVOList(questionAndOptionIdVOList);
                    serviceMap.put(touchServiceBaseName,serviceBean);
                }
            }
        }
        return new ArrayList<>(serviceMap.values());
    }

}
